package com.heima.kafka;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * @author 晓风残月Lx
 * @date 2023/8/10 10:14
 *      生产者
 */
public class ProducerQuickStart {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //1.kafka连接配置信息
        Properties properties = new Properties();
        //kafka连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");

        //ack配置  消息确认机制  默认为1
        properties.put(ProducerConfig.ACKS_CONFIG,"all");
        //数据压缩  默认不压缩
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"snappy");
        //发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,5);

        //消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");

        //2.创建kafka生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        //3.发送消息
        /**
         * 第一个参数 : topic
         * （分区 : 默认为0）
         * 第二个参数 : 消息的key
         * 第三个消息 : 消息的value
         */
        for (int i = 0; i < 5; i++) {
            ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>("itcast-topic-input","hello kafka");
            producer.send(producerRecord);
        }
        //ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>("itcast-topic-input","100001","hello kafka");

        //producer.send(producerRecord);

        //同步发送消息
//        RecordMetadata recordMetadata = producer.send(producerRecord).get();
//        System.out.println(recordMetadata.offset()); //偏移量

        //异步消息发送
//        producer.send(producerRecord, new Callback() {
//            @Override
//            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
//                if (e != null) {
//                    System.out.println("记录异常信息到日志表中");
//                }
//                System.out.println(recordMetadata.offset());
//            }
//        });

        //4.关闭消息通道  必须关闭  否则消息发送不成功
        producer.close();
    }
}
